# 练习使用 Sobel算子

import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

img = cv2.imread('solidYellowCurve.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 计算导数 X 方向
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0)

# 计算导数 Y 方向
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1)

# 计算X绝对值
abs_sobelx = np.absolute(sobelx)

# 转换绝对值图象为8位
scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))

# 设置阈值根据提取强度选择像素
thresh_min = 20
thresh_max = 100
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1

# 可视化输出
plt.imshow(sxbinary, cmap='gray')
plt.show()